<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width;height=device-height;"/>
    <meta name="viewport" content="initial-scale=1.0; maximum-scale=1.0; user-scalable=no;"/>

    <script src="../script/jquery-1.9.1.min.js"></script>
    <script src="../script/vue.min.js"></script>

    <script src="../script/vant.js"></script>
    <script src = "https://gw.alipayobjects.com/as/g/h5-lib/alipayjsapi/3.1.1/alipayjsapi.min.js"> </script>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <link href="../css/vant.css" rel="stylesheet"/>
    <title>账单码</title>
    <style>
        * {
            font-size: 14px;
        }

        body, html {
            margin: 0;
            padding: 0;
            background: #e7e7e7;
            height: 100%;
        }

        .main {
            width: 96%;
            margin: auto;
            height: 98%;
            margin-top: 1%;
            border-radius: 3px;
        }

        .main_top {
            background: #fff;
            border-radius: 5px;
            padding: 10px 0 20px;
            margin-bottom: 5px;
        }

        .main_title {
            text-align: center;
            padding: 5px 0;
            font-weight: 600;
            margin-bottom: 5px;
            background: #fff;
        }

        .main_amt {
            border-radius: 3px;
            text-align: center;
            padding: 5px 0;
            margin-bottom: 5px;
        }

        .main_amt span {
            font-size: 20px;
            color: #f81e1e;
        }

        .main_payamt {
            display: flex;
            justify-content: space-between;
            padding: 20px 20px 10px 20px;
            background: #fff;
            font-weight: 600;
        }

        .main_unpayamt {
            display: flex;
            justify-content: space-between;
            padding: 10px 20px 20px 20px;
            background: #fff;
            margin-bottom: 5px;
            font-weight: 600;
        }

        .main_paytype {
            background: #fff;
            padding: 20px 20px;
        }

        .paytype_item {
            display: flex;
            align-items: center;
            padding: 5px 0;
        }

        .paytype_radius {
            border-radius: 9px;
            width: 16px;
            height: 16px;
            border: 1px solid #ddd;
            margin-right: 15px;
        }

        .tip_radius {
            border-radius: 11px;
            width: 20px;
            height: 20px;
            margin-right: 15px;
            color: #fff;
            background: #0094ff;
            text-align: center;
            line-height: 20px;
        }

        .radius_bg {
            /*background:url(/images/select.png) no-repeat;
            background-size:16px;*/
            background: #0094ff;
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid #0094ff;
        }

        .pay_intput {
            display: flex;
            border-bottom: 1px solid #ddd;
            align-items: center;
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 20px;
        }

        .int_amt {
            border: none;
            outline: none;
            padding: 12px 5px;
        }

        .btn_pay {
            background: #0094ff;
            border-radius: 5px;
            width: 100%;
            height: 44px;
            outline: none;
            border: none;
            margin-top: 30px;
            color: #fff;
            display: block;
            text-align: center;
            line-height: 44px;
        }

        .btn_pay:active {
            background: #326dfa;
        }

        .main_order {
            text-align: center;
        }

        .main_order span {
            font-size: 12px;
        }

        .cl {
            color: #ff6200
        }

        .fsize {
            font-size: 12px;
            color: #333;
            line-height: 20px;
        }

        .pay_right {
            display: flex;
            align-items: center;
        }

        .pay1003 {
            background: url(../images/Wechat.png) no-repeat;
            width: 20px;
            height: 20px;
            background-size: 20px;
            margin-right: 8px;
        }

        .pay1004 {
            background: url(../images/alipay.png) no-repeat;
            width: 20px;
            height: 20px;
            background-size: 20px;
            margin-right: 8px;
        }

        .pay1010 {
            background: url(../images/1010.png) no-repeat;
            width: 20px;
            height: 20px;
            background-size: 20px;
            margin-right: 8px;
        }

        .bg {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.75);
            overflow: hidden;
            display: flex;
            justify-content: center;
        }

        .bg_arrow {
            position: absolute;
            right: 23px;
            top: 10px;
            width: 55px;
            height: 83px;
            background: url(../images/arrow.png) no-repeat;
            background-size: cover;
        }

        .bg_close {
            position: absolute;
            left: 30px;
            top: 50px;
            width: 30px;
            height: 30px;
            background: url(../images/close.png) no-repeat;
            background-size: cover;
        }

        .bg_cont {
            margin-top: 83px;
            color: #fff;
        }

        .insDiv {
            display: flex;
            margin-top: 5px;
        }

        .insDiv_item {
            width: 25%;
            border: 1px solid #326dfa;
            background: #326dfa;
            color: #fff;
            height: 32px;
            line-height: 32px;
            text-align: center;
            margin-right: 20px;
            border-radius: 3px;
        }

        .main_remark {
            margin-top: 5px;
            background: #fff;
            padding: 10px 16px;
            box-sizing: border-box;
        }

        .main_remark_left {
            margin-bottom: 5px;
        }

        .main_remark_right {
            flex: 2;
        }

        .nb {
            border: none;
        }
    </style>
    <script>

        /**
         * 判断当前环境是否为支付宝内置浏览器
         * @returns {boolean} 是支付宝浏览器返回 true，否则返回 false
         */
        function isAlipayBrowser() {
            // 获取当前浏览器的 User Agent 字符串
            const ua = navigator.userAgent;
           // alert(ua);
            // 检查 UA 中是否包含支付宝的特征标识
            // 常见的标识包括：AlipayClient, Alipay, AlipayDefined
            return /AlipayClient|Alipay|AlipayDefined/i.test(ua);
        }
        function loadZfbUserId() {
            ap.getAuthCode ({
                appId :  '2021005185660440' ,
                scopes : ['auth_user'],
            },function(res){
                // ap.alert (JSON.stringify(res));
                // 1. 解析 JSON 字符串
                const data = JSON.parse(JSON.stringify(res));
                // 2. 获取 authcode 字段（注意是小写）
                const authcodes = data.authcode;
                postData(authcodes);
            });

        }

        function postData(authcode) {
            $.ajax({
                url: "https://www.payxiao.com/payServer/payweb/getZfbUserId",
                data: JSON.stringify({ code: authcode }),
                type: "POST",
                dataType: "json",
                contentType: "application/json",
                success: function (data) {
                    const result = data;  //JSON.parse(JSON.stringify(data))
                    if (result && result.data && result.data.openId) {
                        const openId = result.data.openId;
                        document.getElementById('zfbUserId').value = openId;
                    }
                },
                error: function (text) {
                    console.log(text);
                }
            });
        }

        // 由于js的载入是异步的，所以可以通过该方法，当AlipayJSBridgeReady事件发生后，再执行callback方法
        function ready(callback) {
            if (window.AlipayJSBridge) {
                callback && callback();
            } else {
                document.addEventListener('AlipayJSBridgeReady', callback, false);
            }
        }
        function tradePay(tradeNO) {

            ready(function(){
                // 通过传入交易号唤起快捷调用方式(注意tradeNO大小写严格)
                AlipayJSBridge.call("tradePay", {
                    tradeNO: tradeNO
                }, function (data) {
                    log(JSON.stringify(data));
                    if ("9000" == data.resultCode) {
                        console.log('支付成功');
                    }
                });
            });
        }

    </script>

</head>
<body>

<div class="main" id="main">
    <div class="main_top">
        <div class="main_title">
            账单信息
        </div>
        <!--<div class="main_amt">
            <span>￥</span><span>{{orderAmount}}</span>
        </div>-->
        <div class="main_order">
            <span>订单号：</span><span>{{orderId}}</span>
        </div>
    </div>

    <div class="main_payamt">
        <div>
            已支付金额
        </div>
        <div>
            <span>￥</span><span>{{payAmount}}</span>
        </div>
    </div>
    <div class="main_unpayamt">
        <div class="cl">
            未支付金额
        </div>
        <div>
            <span class="cl">￥</span><span class="cl">{{unPayAmount}}</span>
        </div>
    </div>

    <div class="main_paytype">

        <div class="pay_intput">
            <div>￥</div>
            <div><input type="number" class="int_amt" v-model="amount" placeholder="请输入实际支付金额"/></div>
        </div>

        <div class="paytype_item" @click="chosePayType(1003)" v-if="oldPayType==1003">
            <div>
                <div class="paytype_radius" :class="payType==1003?'radius_bg':''">
                    <van-icon name="success" v-if="payType==1003"/>
                </div>
            </div>
            <div class="pay_right">
                <div class="pay1003"></div>
                微信
            </div>
        </div>
        <div class="paytype_item" @click="chosePayType(1004)" v-if="oldPayType==1004 || oldPayType==1003 ">
            <div>
                <div class="paytype_radius" :class="payType==1004?'radius_bg':''">
                    <van-icon name="success" v-if="payType==1004"/>
                </div>
            </div>
            <div class="pay_right">
                <div class="pay1004"></div>
                支付宝
            </div>
        </div>
        <!--<div class="paytype_item" @click="chosePayType(1010)" v-if="oldPayType==1010 ">
            <div><div class="paytype_radius" :class="payType==1010?'radius_bg':''"><van-icon name="success" v-if="payType==1010" /></div></div>
            <div class="pay_right"><div class="pay1010"></div>云闪付</div>
        </div>-->


        <!--<div class="insDiv" v-if="oldPayType==1005">
            <div class="insDiv_item" @click="insNum=3">
                分3期
                <i class="el-icon-check" v-if="insNum==3"></i>
            </div>
            <div class="insDiv_item" @click="insNum=6">
                分6期
                <i class="el-icon-check" v-if="insNum==6"></i>
            </div>
            <div class="insDiv_item" @click="insNum=12">
                分12期
                <i class="el-icon-check" v-if="insNum==12"></i>
            </div>
        </div>-->
    </div>
    <div class="main_remark">

        <div class="main_remark_right">

            <van-cell-group inset>
                <van-field v-model="remark"
                           rows="2"
                           autosize
                           show-word-limit
                           type="textarea"
                           placeholder="可输入备注" maxlength="50"/>
            </van-cell-group>
        </div>
    </div>
    <div class="pay_btn">
        <a class="btn_pay" @click="pay">
            支付
        </a>

    </div>
    <div style="padding: 30px 0 20px 0;">
        <div class="fsize">说明</div>
        <div class="fsize">
            1.支持多次支付，合计为账单总金额。
        </div>
        <div class="fsize">
            2.支持微信，支付宝，云闪付扫码组合支付。
        </div>
    </div>
    <div class="bg" v-if="isShow==true">
        <div class="bg_arrow"></div>
        <div class="bg_close" @click="close"></div>
        <div class="bg_cont">
            <div>如已安装 {{payText}}APP</div>
            <div style="display:flex;padding:5px 0;">
                <div class="tip_radius">1</div>
                请点击右上角的菜单按钮
            </div>
            <div style="display:flex;padding:5px 0;">
                <div class="tip_radius">2</div>
                请选择“在浏览器中打开”
            </div>
        </div>
    </div>
</div>


<script>
    (function ($) {
        $.getUrlParam = function (name) { //获取url 的参数
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) {
                return unescape(r[2]);
            }
            return null;
        }
    })(jQuery);

    function isWeixinBrowser() {
        const ua = navigator.userAgent.toLowerCase();
        return /micromessenger/i.test(ua); // 匹配微信UA
    }

    var vm = new Vue({
        el: '#main',
        data: {

            payAmount: 0,
            unPayAmount: 0,
            orderAmount: 0,
            amount: null,
            orderId: null,
            payType: -1,
            isShow: false,
            payText: "",
            oldPayType: 1004,
            token: null,
            insNum: 3,
            remark: null,
            needRemark: 0,
            tersn: null,
            mersn: null,
            openid: null
        },
        created: function () {

            this.token = $.getUrlParam("token");
            this.payAmount = $.getUrlParam("payAmount");
            this.orderAmount = $.getUrlParam("orderAmount");
            this.orderId = $.getUrlParam("orderid");
            this.needRemark = $.getUrlParam("needRemark");
            this.unPayAmount = (this.orderAmount - this.payAmount).toFixed(2);
            this.tersn = $.getUrlParam("tersn");
            this.mersn = $.getUrlParam("mersn");
            this.openid = $.getUrlParam("openid");
            var userAgent = navigator.userAgent.toLowerCase();
            this.amount = this.unPayAmount;

         //   alert('当前UA:'+userAgent);
         //   alert('是否支付宝环境?', isAlipayBrowser());
            // 确保支付宝环境下强制使用支付宝支付

            // 改进浏览器检测逻辑
            if (userAgent.indexOf("micromessenger") > -1) {
                // 微信浏览器
                this.oldPayType = 1003;
                this.payType = 1003;
                this.payText = "微信";
            } else if (userAgent.indexOf("alipay") > -1) {
                // 支付宝浏览器
                this.oldPayType = 1004;
                this.payType = 1004;
                this.payText = "支付宝";
            } else if (userAgent.indexOf("unionpay") > -1) {
                // 云闪付浏览器
                this.oldPayType = 1010;
                this.payType = 1010;
                this.payText = "云闪付";
            } else {
                // 其他浏览器，从服务器获取支付类型
                var _this = this;


                $.post("/orderPay/GetToken", {token: this.token}, function (res) {
                    if (res.code != 0) return;
                    _this.oldPayType = res.payType;
                    _this.payType = res.payType;
                    _this.amount = res.amount;
                    _this.insNum = res.num;
                    _this.remark = res.remark
                })
            }

            // 确保在支付宝浏览器中强制使用支付宝支付
            if (isAlipayBrowser()) {
                this.oldPayType = 1004;
                this.payType = 1004;
                this.payText = "支付宝";
            }

           // alert('最终payType:'+this.payType); // 验证payType是否为1004

            // if (userAgent.indexOf("micromessenger") > -1) {
            //     this.oldPayType = 1003;
            //
            // } else if (userAgent.indexOf("alipay") > -1) {
            //     this.oldPayType = 1004;
            //     this.payText = "支付宝";
            //
            // } else if (userAgent.indexOf("unionpay") > -1) {
            //     this.oldPayType = 1010;
            //     this.payText = "云闪付";
            // } else {
            //     var _this = this;
            //     $.post("/orderPay/GetToken", {token: this.token}, function (res) {
            //         if (res.code != 0) return;
            //         _this.oldPayType = res.payType;
            //         _this.payType = res.payType;
            //         _this.amount = res.amount;
            //         _this.insNum = res.num;
            //         _this.remark = res.remark
            //     })
            //
            // }
          //  this.payType = this.oldPayType;

        },
        methods: {
            close: function () {
                this.isShow = false;
            },
            chosePayType: function (payType) {

                if (this.unPayAmount == 0) {
                    this.$toast.fail('账单支付已完成，请勿重复支付');
                    return;
                }

                if (!this.amount || this.amount == 0) {
                    this.$toast.fail('请输入支付金额');
                    return;
                }
                if (Number(this.amount) > Number(this.unPayAmount)) {
                    this.$toast.fail('支付金额不能大于未支付金额');
                    return;
                }

                this.payType = payType;
                if (payType == 1004 || payType == 1005) {

                    this.payText = "支付宝";

                }

                if (payType == 1010 || payType == 1033) {

                    this.payText = "云闪付";
                }
                if (payType != this.oldPayType && payType != 1003 && payType != 1033) {

                    var _this = this;
                    $.post("/orderPay/ChosePayType", {
                        token: this.token,
                        amount: this.amount,
                        payType: this.payType,
                        insNum: this.insNum,
                        remark: this.remark
                    }, function (res) {
                        if (res.code != 0) {

                            return;
                        }
                        if (this.oldPayType != 1003)
                            _this.isShow = true;
                    })

                }
            },
            pay: function () {
                if (this.unPayAmount == 0) {
                    this.$toast.fail('账单支付已完成，请勿重复支付');
                    return;
                }
                if (!this.amount || this.amount == 0) {
                    this.$toast.fail('请输入支付金额');
                    return;
                }
                if (Number(this.amount) > Number(this.unPayAmount)) {
                    this.$toast.fail('支付金额不能大于未支付金额');
                    return;
                }
                if (this.needRemark == 1 && !this.remark) {
                    this.$toast.fail('必须填写备注');
                    return;
                }

                var thata = this;
                var res =null;
                if(isAlipayBrowser()){
                    loadZfbUserId();
                    var openids=''; //document.getElementById('zfbUserId').value
                    var zfbUserId=document.getElementById('zfbUserId').value;
                    if(typeof this.openid !== 'undefined' && this.openid !== null && this.openid !== ''){
                        openids=this.openid;
                    } else  if(typeof zfbUserId !== 'undefined' && zfbUserId !== null && zfbUserId !== ''){
                        openids=zfbUserId;
                    }
                     res = $.get("/orderpay", {
                        amount: this.amount,
                        payType: this.payType,
                        remark: this.remark,
                        tersn: this.tersn,
                        mersn: this.mersn,
                        orderid: this.orderId,
                        openid: openids,
                    }, function (res) {
                        if (res.code != 0) {
                                if(res.data.codeUrl==null||res.data.codeUrl==''){
                                    tradePay(res.data.tradeNo);
                                } else{
                                    window.location.href = res.data.codeUrl;
                                }

                            return;
                        }

                    })
                } else {
                    // 微信/其他环境的支付逻辑（保留微信支付判断）
                    $.get("/orderpay", {
                        amount: this.amount,
                        payType: this.payType,
                        remark: this.remark,
                        tersn: this.tersn,
                        mersn: this.mersn,
                        orderid: this.orderId,
                        openid: this.openid,
                    }, function (res) {
                        if (res.code != 0) {
                            if (thata.payType == 1003) { // 仅微信环境执行此分支
                                var args = JSON.parse(res.data.payInfo);
                                callPay(function () {
                                    try {
                                        WeixinJSBridge.invoke('getBrandWCPayRequest', {
                                            "appId": args.appId,
                                            "timeStamp": args.timeStamp,
                                            "nonceStr": args.nonceStr,
                                            "package": args.package,
                                            "signType": args.signType,
                                            "paySign": args.paySign
                                        }, function (res) {
                                            // 微信支付结果处理...
                                        });
                                    } catch (e) {
                                        _this.$toast.fail(e);
                                    }
                                });
                                return;
                            } else {
                                if (res.data.codeUrl) {
                                    window.location.href = res.data.codeUrl;
                                }
                            }
                            return;
                        }
                    });
                }

            },

        },
        watch: {
            amount: function (newVal, olVal) {
                var rel = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/
                if (!newVal.match(rel) && newVal != "") {
                    this.amount = olVal;

                }
            }
        }

    })

function callPay(callback) {
    if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', callback, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', callback);
            document.attachEvent('onWeixinJSBridgeReady', callback);
        }
    } else {
        callback();
    }
}
</script>
<span id="zfbUserId" hidden style="display:none;"></span>
</body>
</html>
